// pages/user/user-info-edit/user-info-edit.page.ts

import { User } from "../../../models/user.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UserService } from "../../../services/user.service";

const defaultAvatarUrl = `/assets/avatar.png`;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setNavigationBarTitle({
      title: '修改个人信息'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const userInfo = LocalStorage.getUserInfo();
    if (userInfo) {
      this.setData({
        userInfo: {
          avatarUrl: !!userInfo.avatarUrl ? `${GlobalService.STATIC_FILE_HOST}${userInfo.avatarUrl}` : defaultAvatarUrl,
          nickName: !!userInfo.nickName ? userInfo.nickName : ''
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail;
    GlobalService.uploadImage(avatarUrl).then(async (url: string) => {
      console.log(url);
      if (url.indexOf('/avatars') > -1) {
        const userInfo = LocalStorage.getUserInfo();
        if (userInfo) {
          userInfo.avatarUrl = url;
          const updatedUserInfo = await UserService.updateUserInfo(userInfo);
          LocalStorage.setUserInfo(updatedUserInfo);
          this.setData({
            "userInfo.avatarUrl": `${GlobalService.FILE_HOST}${updatedUserInfo.avatarUrl}`,
          });
        }
      }
    });
  },
  async onInputChange(e: any) {
    const nickName = e.detail.value;
    const userInfo: User | undefined = LocalStorage.getUserInfo();
    if (!userInfo) {
      return;
    }
    userInfo.nickName = nickName;
    let updatedUserInfo = await UserService.updateUserInfo(userInfo);
    LocalStorage.setUserInfo(updatedUserInfo);
    this.setData({
      "userInfo.nickName": nickName,
    });
  },
})